#include <queue>
#include <pthread.h>

template<class T>
class blockQueue
{
    typedef const T const_T;
    static const int default_maxcap = 5;
public:

    blockQueue(int _maxcap = default_maxcap)
        :_maxcap(default_maxcap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_ccond, nullptr);
        pthread_cond_init(&_pcond, nullptr);
    }

    const_T pop()
    {
        pthread_mutex_lock(&_mutex);
        while (_block.size() <= 0) //使用while防止线程被伪唤醒的情况
        {
            pthread_cond_wait(&_pcond, &_mutex);
        }
        T out = _block.front();
        _block.pop();
        pthread_cond_signal(&_ccond);
        pthread_mutex_unlock(&_mutex);
        return out;
    }

    bool push(const_T& in)
    {
        pthread_mutex_lock(&_mutex);
        while (_block.size() >= _maxcap)
        {
            pthread_cond_wait(&_ccond, &_mutex);
        }
        _block.push(in);
        pthread_cond_signal(&_pcond);
        pthread_mutex_unlock(&_mutex);
    }

    ~blockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_ccond);
        pthread_cond_destroy(&_pcond);
    }

private:
    std::queue<T> _block;   //共享资源
    int _maxcap;    //队列极值
    pthread_mutex_t _mutex;     //互斥锁
    pthread_cond_t _ccond;       //条件变量
    pthread_cond_t _pcond;
};